<?php
/**
 *
 * @Allan
 * Date: 2020/12/4 12:31
 */

namespace app\common\traits;


use app\common\utils\Functions;
use app\common\model\Sport\Club as SportClubModel;
use app\common\model\Sport\Team as SportTeamModel;
use think\Exception;
use think\Log;

trait SportClub
{

    /**
     * 查询 资源
     * @param array $param
     * @return SportScoreModel
     */
    private static function query($param = []){

        $query = SportClubModel::where([]);

        if(isset($param['id']) && !empty($param['id'])){
            $query->where('id','=',intval($param['id']));
        }

        if(isset($param['type']) && !empty($param['type'])){
            $query->where('type','=',intval($param['type']));
        }

        if(isset($param['version']) && !empty($param['version'])){
            $query->where('version','=',trim($param['version']));
        }

        if(isset($param['country_id']) && !empty($param['country_id'])){
            $query->where('country_id','=',intval($param['country_id']));
        }

        if(isset($param['name']) && !empty($param['name'])){
            $query->where('name','=',trim($param['name']));
        }
        if(isset($param['full_name']) && !empty($param['full_name'])){
            $query->where('full_name','like','%'.trim($param['full_name']).'%');
        }

        if(isset($param['update_time_start']) && !empty($param['update_time_start'])){
            $query->where('update_time','>=',($param['update_time_start']));
        }
        if(isset($param['update_time_end']) && !empty($param['update_time_end'])){
            $query->where('update_time','<',($param['update_time_end']).' 23:59:59');
        }


        return $query;

    }

    /**
     * 获取列表数据
     * @param array $param
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($param = []){

        $is_get_all = $param['is_get_all'] ?? 0; //获取所有

        $query = self::query($param);


        $order = $param['order'] ?? 'id desc';
        $order = explode(' ',$order);


        $page = intval($param['page'] ?? 1);
        $per_page = intval($param['per_page'] ?? 1);
        $per_page = $per_page < 1 ? 10: $per_page;

        $total = $query->count();
//        Log::error($query->getLastSql());

        if($is_get_all) $per_page = $total;

        $query = self::query($param);
        $query = $query->order($order[0] ?? 'id' , $order[1] ?? 'desc' );
        $list = $query->page($page,$per_page)->select();
//        Log::error($query->getLastSql());

        $list = $list ? collection($list)->toArray() : [];
        $list = self::formatList($list);

        return Functions::formatList($list,$page,$per_page,$total,true);
    }

    /**
     * 获取详情
     * @param $id
     * @param array $param
     * sn 单据号
     * @return bool
     */
    public function getDetail($id){
        $id = intval($id);
        if( $id <= 0 ) throw new Exception('参数错误',config('error_code.error'));
        $operator_id = intval(session('admin_id') ?? 0);
//        if( empty($operator_id) ) throw new Exception('操作人不能为空',config('error_code.error'));


        $obj = SportClubModel::get($id);
        $data = $obj ? $obj->toArray() : null;
        return self::formatInfo($data,$operator_id);

    }


    /**
     * 添加对象
     * @param array $param
     */
    public static function add($param = []){

        $country_id =  intval($param['country_id']);
        $name =  trim($param['name']);
        $full_name =  trim($param['full_name']);

        if(empty($type)) throw new \Exception('所属类型不能为空',config('error_code.error'));
        if(empty($country_id)) throw new \Exception('所属地区不能为空',config('error_code.error'));
        if(empty($name)) throw new \Exception('名称不能为空',config('error_code.error'));
        if(empty($full_name)) throw new \Exception('全称不能为空',config('error_code.error'));

        $isExist = SportClubModel::where('type','=',$type)
            ->where('country_id','=',$country_id)
            ->where('name','=',$name)
            ->count();

        if( $isExist>0 ) throw new \Exception('名称已存在',config('error_code.error'));
        
        $model = new SportClubModel();
        $model->name = $name;
        $model->full_name = $full_name;

        $model->type = $type;
        $model->country_id = $country_id;
        $model->country_name = config('other.country')[$country_id];

        $model->update_user = trim(session('admin_user') ?? '');//录单人
        $model->update_user_id = trim(session('admin_id') ?? 0);//录单人
        $model->update_time = time();

        $model->create_user = $model->update_user ;//录单人
        $model->create_user_id = $model->update_user_id;//录单人
//        $model->create_time = $model->update_time;

        $model->save();
        $id = $model->id;
        if( $id<=0 ) throw new \Exception('添加失败',config('error_code.error'));


        return [
            'id' => $id,
        ];

    }


    /**
     * 编辑对象
     * @param array $param
     * @param $id
     */
    public static function edit($param = []){

        $id = intval($param['id']);
        $obj = SportClubModel::get($id);
        if(empty($obj)) throw new \Exception('球队俱乐部不存在',config('error_code.error'));

        if( isset($param['type']) && $param['type'] ) $obj->type = intval($param['type']);

        if( isset($param['country_id']) ){
            $country_id =  intval($param['country_id']);
            $obj->country_id = $country_id;
            $obj->country_name = config('other.country')[$country_id];
        }

        if( isset($param['name']) ){
            $name =  trim($param['name']);
            if( empty($name) ) throw new \Exception('名称不能为空',config('error_code.error'));
            $isExist = SportClubModel::where('id','<>',$id)
                ->where('type','=',$obj->type)
                ->where('country_id','=',$obj->country_id)
                ->where('name','=',$name)
                ->count();
            if( $isExist>0 ) throw new \Exception('名称已存在',config('error_code.error'));
            $obj->name = $name;
        }

        if( isset($param['full_name']) ){
            $full_name =  trim($param['full_name']);
            $isExist = SportClubModel::where('id','<>',$id)
                ->where('type','=',$obj->type)
                ->where('country_id','=',$obj->country_id)
                ->where('full_name','=',$full_name)
                ->count();
            if( $isExist>0 ) throw new \Exception('全称已存在',config('error_code.error'));
            $obj->full_name = $full_name;
        }

        $obj->update_user = trim(session('admin_user') ?? '');//录单人
        $obj->update_user_id = trim(session('admin_id') ?? 0);//录单人
        $obj->update_time = time();

        $obj->save();



        return [
            'id' => $id,
        ];
    }

    /**
     * 验证是否可删除
     * @param $id 俱乐部id
     * @return bool
     */
    public static function canDelete($id){
        if(SportTeamModel::where('club_id','=',$id)->count() > 0) return false;
        return true;
    }

    /**
     * 删除记录
     * @param $id
     * @return bool
     */
    public static function delete($param){

        $id = $param['id'] ?? '';
        if ( empty($id) ) throw new \Exception('参数错误',config('error_code.error'));


        if( is_numeric($id) ){
            if( !self::canDelete($id) ) throw new \Exception('已关联球队，不可删除',config('error_code.error'));
            SportClubModel::destroy(['id'=>$id]);
        }else{
            $ids = explode(',',trim($id));
            foreach ($ids as $id){
                if( !self::canDelete($id) ) throw new \Exception('已关联球队，不可删除',config('error_code.error'));
                SportClubModel::destroy(['id'=>$id]);
            }
        }
        return  true;
    }

    /**
     * 格式化
     * @param $value
     * @return mixed
     */
    public static function format($value){
        if(isset($value['create_time'])) $value['create_time'] = Functions::formatDateTime($value['create_time']);
        if(isset($value['update_time'])) $value['update_time'] = Functions::formatDateTime($value['update_time']);

        if(isset($value['type'])) $value['type_name'] = (new SportClubModel)->getTypeList()[$value['type']] ?? '无';


        return $value;
    }

    /**
     * 格式化 info
     * @param $info
     */
    public static function formatInfo($info){
        if(!empty($info)){
            $info = self::format($info);
        }
        return $info;
    }

    /**
     * 格式化 list
     * @param $list
     * @param bool $isGetAssetsSn 是否获取 支出的资产编号 默认否
     * @return mixed
     */
    public static function formatList($list){

        if(!empty($list)){
            foreach ($list as $key => &$value){
                $value = self::format($value);
            }
        }
        return $list;
    }


}